package edu.gatech.gro;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import edu.gatech.gro.http.IResponseAdapter;
import edu.gatech.gro.model.NamedList;
import edu.gatech.gro.model.ObjectResponse;

public class NamedListDisplayActivity extends Activity {

	private static final String TAG = "NAMED_LIST_DISPLAY_ACTIVITY";

	private final IncomingHandler mHandler = new IncomingHandler();

	private static final int GOT_NAMED_LIST = 0;

	private static final int NAMED_LIST_CREATED = 10;
	private static final int NAMED_LIST_UPDATED = 11;
	private static final int NAMED_LIST_DELETED = 12;

	private static GroceryListManagerApplication app;

	private Button mAddNamedListButton;
	private ListView mNamedLists;

	private AlertDialog mAlertDialog;
	private ProgressDialog mProgressNamedList;
	private ProgressDialog mProgressDelete;

	private ArrayList<NamedList> mCurrentNamedLists;
	private int mUserId;
	private NamedList mCurrentNamedList;
	private NamedList mLastNamedListDeleted;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		app = (GroceryListManagerApplication) getApplicationContext();

		setContentView(R.layout.named_list_manager);

		mAlertDialog = new AlertDialog.Builder(NamedListDisplayActivity.this).create();
		mAlertDialog.setButton("OK", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});

		Bundle extra = getIntent().getExtras();
		mUserId = extra.getInt("userId");

		mAddNamedListButton = (Button) findViewById(R.id.addNamedListButton);
		mNamedLists = (ListView) findViewById(R.id.namedLists);

		mAddNamedListButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.d(TAG, "mAddNamedListButton clicked");
				mCurrentNamedList = null;
				displayNamedListAdderPanel();
			}
		});
	}

	@Override
	public void onResume() {
		super.onResume();
		waitForNamedLists();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
			case NAMED_LIST_UPDATED:
				if (resultCode == RESULT_OK) {
					Bundle b = data.getExtras();
					updateNamedListAfterEdit(b.getString("name"));
				}
				break;
		}

	}

	private void updateNamedListAfterEdit(String name) {
		mCurrentNamedList.setName(name);
		mNamedListAdapter.notifyDataSetChanged();
	}

	private void waitForNamedLists() {
		if (mProgressNamedList != null && mProgressNamedList.isShowing()) {
			return;
		}

		mProgressNamedList = ProgressDialog.show(NamedListDisplayActivity.this, "", // this.getString(R.string.pleaseWait),
		    this.getString(R.string.progressNamedList), true, false);

		app.getAllNamedList(mUserId, mNamedListsListener);
	}

	private void waitForDeleteNamedList() {
		if (mProgressDelete != null && mProgressDelete.isShowing()) {
			return;
		}

		mProgressDelete = ProgressDialog.show(NamedListDisplayActivity.this, "", // this.getString(R.string.pleaseWait),
		    this.getString(R.string.progressUserDelete), true, false);

		mLastNamedListDeleted = mCurrentNamedList;
		app.deleteNamedList(mCurrentNamedList, mDeleteListener);
	}

	private void refreshNamedLists() {
		if (mCurrentNamedLists != null && mCurrentNamedLists.size() > 0) {
			mNamedListAdapter = new NamedListAdapter(NamedListDisplayActivity.this, R.layout.named_list_item, mCurrentNamedLists);
			mNamedLists.setAdapter(mNamedListAdapter);
		}
	}

	private void displayNamedListAdderPanel() {
		Intent i = new Intent(this, NamedListEditActivity.class);
		i.putExtra("hasNamedList", mCurrentNamedList != null);
		i.putExtra("userId", mUserId);
		if (mCurrentNamedList == null) {
			startActivityForResult(i, NAMED_LIST_CREATED);
		} else {
			i.putExtra("listId", mCurrentNamedList.getId());
			i.putExtra("listName", mCurrentNamedList.getName());
			startActivityForResult(i, NAMED_LIST_UPDATED);
		}
	}

	private void displayItems(NamedList nl) {
		Intent i = new Intent(this, ItemDisplayActivity.class);
		i.putExtra("userId", mUserId);
		i.putExtra("namedListId", nl.getId());
		i.putExtra("namedListName", nl.getName());
		i.putExtra("namedListNameClean", nl.getNameClean());
		startActivity(i);
	}

	private void editNamedList(NamedList list) {
		mCurrentNamedList = list;
		displayNamedListAdderPanel();
	}

	private void deleteNamedList(NamedList list) {
		mCurrentNamedList = list;
		waitForDeleteNamedList();
	}

	private void promptAvailableActions(final NamedList list) {
		String[] items = new String[2];
		items[0] = this.getString(R.string.edit);
		items[1] = this.getString(R.string.delete);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.whattodo);
		builder.setItems(items, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int item) {
				switch (item) {
					case 0: // Edit
						editNamedList(list);
						break;
					case 1: // Delete
						deleteNamedList(list);
						break;
				}
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	private final IResponseAdapter mNamedListsListener = new IResponseAdapter() {

		@Override
		public void onResponse(ObjectResponse obj) {
			dismissProgress(mProgressNamedList);
			if (obj.isSuccessful()) {
				// Save the current list of users
				mCurrentNamedLists = (ArrayList<NamedList>) obj.getData();
				Log.d(TAG, "Named lists received!");
				mHandler.sendEmptyMessage(GOT_NAMED_LIST);
			} else {
				displayError(R.string.failRetrieveListsTitle, obj.getErrorsAsString());
			}
		}
	};

	private final IResponseAdapter mDeleteListener = new IResponseAdapter() {

		@Override
		public void onResponse(ObjectResponse response) {
			dismissProgress(mProgressDelete);
			if (response.isSuccessful()) {
				mHandler.sendEmptyMessage(NAMED_LIST_DELETED);
			} else {
				mLastNamedListDeleted = null;
			}
		}

	};

	/**
	 * Helper function to dismiss a progress dialog
	 * 
	 * @param theProgress
	 *          the progress dialog to dismiss
	 */
	private void dismissProgress(ProgressDialog theProgress) {
		if (theProgress != null && theProgress.isShowing()) {
			theProgress.dismiss();
		}
	}

	/**
	 * Handler of incoming messages from the Service
	 */
	private class IncomingHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case GOT_NAMED_LIST:
					refreshNamedLists();
					break;
				case NAMED_LIST_DELETED:
					if (mLastNamedListDeleted != null) {
						mCurrentNamedLists.remove(mLastNamedListDeleted);
						mNamedListAdapter.notifyDataSetChanged();
						mLastNamedListDeleted = null;
						mCurrentNamedList = null;
					}
					break;
				default:
					super.handleMessage(msg);
					break;
			}
		}
	}

	private void displayError(final int titleId, final String message) {
		mAlertDialog.setTitle(titleId);
		mAlertDialog.setMessage(message);
		mAlertDialog.show();
	}

	private NamedListAdapter mNamedListAdapter;

	private class NamedListAdapter extends ArrayAdapter<NamedList> {

		private final ArrayList<NamedList> mLists;

		public NamedListAdapter(Context context, int textViewResourceId, ArrayList<NamedList> items) {
			super(context, textViewResourceId, items);
			this.mLists = items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.named_list_item, null);
			}
			final NamedList nl = mLists.get(position);
			if (nl != null) {
				TextView tt = (TextView) v.findViewById(R.id.named_list_item_line1);
				TextView bt = (TextView) v.findViewById(R.id.named_list_item_line2);
				if (tt != null) {
					tt.setText(nl.getName());
				}
				if (bt != null) {
					// bt.setText(nl.getEmail());
				}
				tt.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						Log.d(TAG, "named list #" + nl.getId() + " clicked!");
						displayItems(nl);
					}
				});

				tt.setOnLongClickListener(new View.OnLongClickListener() {
					@Override
					public boolean onLongClick(View v) {
						Log.d(TAG, "Long click on list #" + nl.getId());
						promptAvailableActions(nl);
						return false;
					}
				});
			}
			return v;
		}
	}
}
